from django.http import JsonResponse
from django.shortcuts import render, redirect, get_object_or_404
from .models import Article, Tag


def article_list(request):
    articles = Article.objects.all()
    return render(request, 'article_list.html', {'articles': articles})


def create_article(request):
    if request.method == 'POST':
        title = request.POST.get('title')
        content = request.POST.get('content')
        tag_ids = request.POST.getlist('tags')
        article = Article.objects.create(title=title, content=content)
        for tag_id in tag_ids:
            tag = Tag.objects.get(id=tag_id)
            article.tags.add(tag)
        return redirect('article_list')
    tags = Tag.objects.all()
    return render(request, 'create_article.html', {'tags': tags})


def get_tags(request):
    tags = Tag.objects.all()
    tag_list = [{'id': tag.id, 'name': tag.name} for tag in tags]
    return JsonResponse({'tags': tag_list})


def edit_article(request, article_id):
    article = Article.objects.get(id=article_id)
    if request.method == 'POST':
        title = request.POST.get('title')
        content = request.POST.get('content')
        tag_ids = request.POST.getlist('tags')
        article.title = title
        article.content = content
        article.tags.clear()
        for tag_id in tag_ids:
            tag = Tag.objects.get(id=tag_id)
            article.tags.add(tag)
        article.save()
        return redirect('article_list')
    tags = Tag.objects.all()
    return render(request, 'edit_article.html', {'article': article, 'tags': tags})


def create_tag(request):
    if request.method == 'POST':
        tag_name = request.POST.get('tag_name')
        if tag_name:
            Tag.objects.create(name=tag_name)
        return redirect('article_list')
    return render(request, 'create_tag.html')


def delete_article(request, article_id):
    article = get_object_or_404(Article, id=article_id)
    article.delete()
    return redirect('article_list')
